using System;
using System.Threading;
using System.Windows;
using System.Runtime.InteropServices;
using MaterialDesignThemes.Wpf;
using NLog;
using System.IO;

namespace LDNS.UI
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// 作者: huobing
    /// </summary>
    public partial class App : System.Windows.Application
    {
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();
        private const string UniqueAppId = "LDNS.UI.Application"; // 应用程序唯一标识符
        private Mutex? _mutex;

        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        private static extern IntPtr FindWindow(string? lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        protected override void OnStartup(System.Windows.StartupEventArgs e)
        {
            try
            {
                // 设置LDNS_DIR环境变量
                string programFilesLdnsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "LDNS");
                if (!string.Equals(AppContext.BaseDirectory.TrimEnd('\\'), programFilesLdnsPath, StringComparison.OrdinalIgnoreCase))
                {
                    // 非标准安装目录，设置LDNS_DIR环境变量
                    Environment.SetEnvironmentVariable("LDNS_DIR", AppContext.BaseDirectory);
                }
                
                // 确保使用LDNS.UI.Nlog.config配置文件
                var configFilePath = Path.Combine(AppContext.BaseDirectory, "LDNS.UI.Nlog.config");
                if (File.Exists(configFilePath))
                {
                    NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(configFilePath);
                }
                
                // 添加调试日志
                _logger.Info("App.OnStartup开始执行");
                
                // 检查是否已有实例在运行
                bool createdNew;
                _mutex = new Mutex(true, UniqueAppId, out createdNew);
                _logger.Info($"互斥锁创建结果: {createdNew}");

                if (!createdNew)
                {
                    // 已有实例在运行，激活已有窗口并退出当前实例
                    _logger.Info("检测到已有实例在运行，尝试激活");
                    ActivateExistingInstance();
                    this.Shutdown();
                    return;
                }

                // 初始化应用程序
                _logger.Info("启动新实例，调用base.OnStartup");
                base.OnStartup(e);
                _logger.Info("App.OnStartup执行完成");
            }
            catch (Exception ex)
            {
                _logger.Info($"App.OnStartup异常: {ex.Message}");
                _logger.Info(ex.StackTrace ?? "");
                MessageBox.Show($"应用程序启动错误: {ex.Message}\n\n{ex.StackTrace}", "启动错误", MessageBoxButton.OK, MessageBoxImage.Error);
                this.Shutdown(1);
            }
        }

        private void ActivateExistingInstance()
        {
            try
            {
                // 尝试获取已存在的实例窗口句柄
                IntPtr existingWindowHandle = FindWindow(null, "Local DNS Service Manager");
                _logger.Info(existingWindowHandle.ToString() ?? "0"); // 添加null检查
                if (existingWindowHandle != IntPtr.Zero)
                {
                    ShowWindow(existingWindowHandle, 1); // SW_SHOWNORMAL = 1
                    SetForegroundWindow(existingWindowHandle);
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "激活现有实例时出错");
            }
        }

        protected override void OnExit(ExitEventArgs e)
        {
            if (_mutex != null)
            {
                _mutex.ReleaseMutex();
                _mutex.Dispose();
            }
            base.OnExit(e);
        }
    }
}